/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.config.service.impl;


import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.HttpUtils;
import com.icinfo.cloud.provider.punish.config.dto.ConfigPaymentChannelInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigPaymentChannelInfoMapper;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigPaymentChannelItemDetailMapper;
import com.icinfo.cloud.provider.punish.config.model.BasicResultInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigPaymentChannelInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigPaymentChannelItemDetail;
import com.icinfo.cloud.provider.punish.config.model.ProjectResultInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigPaymentChannelInfoService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigPaymentChannelInfoVo;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.CasePaymentEntRelatedBasicInfoQueryDto;
import com.icinfo.cloud.provider.punish.ucase.punishdecide.service.impl.PunishDecideServiceImpl;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.File;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述: 缴费渠道信息配置表 config_payment_channel_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年03月01日
 */
@Service
@Slf4j
public class ConfigPaymentChannelInfoServiceImpl extends MyBatisServiceSupport implements IConfigPaymentChannelInfoService {
    private static String CHANNEL_NO = "330000022";
    @Resource
    private ConfigPaymentChannelInfoMapper configPaymentChannelInfoMapper;
    @Resource
    private ConfigPaymentChannelItemDetailMapper configPaymentChannelItemDetailMapper;
    @Resource
    private PunishDecideServiceImpl punishDecideServiceImpl;

    /**
     * 描述：查询缴费渠道配置信息
     *
     * @param queryDto {@link CasePaymentEntRelatedBasicInfoQueryDto}
     * @return {@link List< ConfigPaymentChannelInfoVo >} 缴费渠道配置信息
     * @author xiangyuyu
     * @date 2022-03-15 10:21
     */
    private List<ConfigPaymentChannelInfoVo> getConfigPaymentChannelInfo(CasePaymentEntRelatedBasicInfoQueryDto queryDto) {
        // FIXME: 2022/3/15 调用webservice接口获取统一支付平台缴款单位关联基础信息
        // FIXME: 2022/9/5 暂时使用公共支付模块（消防监督执法系统部署的），后期等webservice剥离开了之后使用对应公共服务
        String url = "http://10.145.147.112:8581/proxy/payAddr/payment/common/getBasicResultInfoList";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("channelNo", queryDto.getOriginalNoticeNo());
        String jsonStr = jsonObject.toJSONString();
        List<ConfigPaymentChannelInfoVo> configPaymentChannelInfoList = new ArrayList<>();
        try {
            log.info("getConfigPaymentChannelInfo param:{}", jsonStr);
            String result = HttpUtils.doPostJson(url, jsonStr);
            /*String result = "{\"code\":200,\"message\":\"\",\"errors\":[],\"data\":[{\"channelNo\":\"330000022\",\"channelName\":\"浙江省统一行政处罚办案系统\",\"regiCode\":\"331126\",\"regiName\":\"庆元县\",\"enteCode\":\"683001\",\"enteName\":\"庆元县黄田镇人民政府\",\"list\":[{\"chitCode\":\"08501010\",\"chitName\":\"罚没收入\",\"initCode\":\"10601\",\"initName\":\"行政处罚罚没收入\",\"sectionCode\":\"103050199\",\"sectionName\":\"其他一般罚没收入\",\"standardType\":\"2\",\"fixStandard\":\"0\",\"maxStandard\":\"10000000000\",\"minStandard\":\"0\"},{\"chitCode\":\"08500581\",\"chitName\":\"代管及往来\",\"initCode\":\"2010101\",\"initName\":\"代管及往来\",\"sectionCode\":null,\"sectionName\":null,\"standardType\":\"2\",\"fixStandard\":\"0\",\"maxStandard\":\"100000000\",\"minStandard\":\"0\"},{\"chitCode\":\"08500582\",\"chitName\":\"一般往来（非经营服务性收入）\",\"initCode\":\"2010102\",\"initName\":\"一般往来（非经营服务性收入）\",\"sectionCode\":null,\"sectionName\":null,\"standardType\":\"2\",\"fixStandard\":\"0\",\"maxStandard\":\"100000000\",\"minStandard\":\"0\"}]}]}";*/
            if (!ObjectUtils.isEmpty(result)) {
                JSONObject resultJO = JSONObject.parseObject(result);
                if (!ObjectUtils.isEmpty(resultJO)) {
                    Object code = resultJO.get(Constant.STRING_CODE_LOWER);
                    if (!ObjectUtils.isEmpty(code) && HttpStatus.HTTP_OK == (int) code) {
                        Object data = resultJO.get(Constant.STRING_DATA_LOWER);
                        if (ObjectUtils.isEmpty(data)) {
                            log.error("getConfigPaymentChannelInfo 相应data为null,msg:{}", resultJO.getString(Constant.STRING_MSG_LOWER));
                            throw new BusinessException("getConfigPaymentChannelInfo 相应data为null,msg:" + resultJO.getString(Constant.STRING_MSG_LOWER));
                        } else {
                            List<JSONObject> list = (List<JSONObject>) data;
                            if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                                list.forEach(e -> {
                                    BasicResultInfo basicResultInfo = JSONObject.toJavaObject(e,BasicResultInfo.class);
                                    List<ProjectResultInfo> itemList = basicResultInfo.getList();
                                    if (!ObjectUtils.isEmpty(itemList) && itemList.size() > 0) {
                                        itemList.forEach(ele -> {
                                            String chitName = ele.getChitName();
                                            if ("罚没收入".equals(chitName)) {
                                                ConfigPaymentChannelInfoVo configPaymentChannelInfoVo = new ConfigPaymentChannelInfoVo();
                                                configPaymentChannelInfoVo.setEnterCode(basicResultInfo.getEnteCode());
                                                configPaymentChannelInfoVo.setEnterName(basicResultInfo.getEnteName());
                                                configPaymentChannelInfoVo.setRegiCode(basicResultInfo.getRegiCode());
                                                configPaymentChannelInfoVo.setRegiName(basicResultInfo.getRegiName());
                                                configPaymentChannelInfoVo.setDefaultChitCode(ele.getChitCode());
                                                configPaymentChannelInfoVo.setDefaultChitName(ele.getChitName());
                                                configPaymentChannelInfoList.add(configPaymentChannelInfoVo);
                                            }
                                        });
                                    }
                                });
                            }
                        }
                    } else {
                        log.error("getConfigPaymentChannelInfo 响应code:{},msg:{}", code, resultJO.getString(Constant.STRING_MESSAGE_LOWER));
                        throw new BusinessException("getConfigPaymentChannelInfo 响应code:" + code + ",msg:" + resultJO.getString(Constant.STRING_MESSAGE_LOWER));
                    }
                } else {
                    log.error("getConfigPaymentChannelInfo error(result transform JSONObject)");
                    throw new BusinessException("getConfigPaymentChannelInfo error(result transform JSONObject");
                }
            } else {
                log.error("getConfigPaymentChannelInfo result:null");
                throw new BusinessException("getConfigPaymentChannelInfo result:null");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            throw new BusinessException("查询缴费渠道配置信息时出现异常 " + e.getMessage());
        }
        // FIXME: 2022/3/21  先从省统一处罚正式库拿到xml数据，进行本地解析
        //configPaymentChannelInfoList = analyseUnitBasicInfo();
        return configPaymentChannelInfoList;
    }

    /**
     * 描述：查询缴费渠道配置信息-区域信息
     *
     * @param queryDto {@link CasePaymentEntRelatedBasicInfoQueryDto}
     * @return {@link List< ConfigPaymentChannelInfoVo >} 缴费渠道配置信息
     * @author xiangyuyu
     * @date 2022-03-15 10:21
     */
    private List<ConfigPaymentChannelInfoVo> getConfigPaymentChannelInfoRegiInfo(CasePaymentEntRelatedBasicInfoQueryDto queryDto) {
        // FIXME: 2022/3/15 调用webservice接口获取统一支付平台缴款单位关联基础信息
        // FIXME: 2022/9/5 暂时使用公共支付模块（消防监督执法系统部署的），后期等webservice剥离开了之后使用对应公共服务
        String url = "http://10.145.147.112:8581/proxy/payAddr/payment/common/getBasicResultInfoList";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("channelNo", queryDto.getOriginalNoticeNo());
        String jsonStr = jsonObject.toJSONString();
        List<ConfigPaymentChannelInfoVo> configPaymentChannelInfoList = new ArrayList<>();
        try {
            log.info("getConfigPaymentChannelInfoRegiInfo param:{}", jsonStr);
            String result = HttpUtils.doPostJson(url, jsonStr);
            /*String result = "{\"code\":200,\"message\":\"\",\"errors\":[],\"data\":[{\"channelNo\":\"330000022\",\"channelName\":\"浙江省统一行政处罚办案系统\",\"regiCode\":\"331126\",\"regiName\":\"庆元县\",\"enteCode\":\"683001\",\"enteName\":\"庆元县黄田镇人民政府\",\"list\":[{\"chitCode\":\"08501010\",\"chitName\":\"罚没收入\",\"initCode\":\"10601\",\"initName\":\"行政处罚罚没收入\",\"sectionCode\":\"103050199\",\"sectionName\":\"其他一般罚没收入\",\"standardType\":\"2\",\"fixStandard\":\"0\",\"maxStandard\":\"10000000000\",\"minStandard\":\"0\"},{\"chitCode\":\"08500581\",\"chitName\":\"代管及往来\",\"initCode\":\"2010101\",\"initName\":\"代管及往来\",\"sectionCode\":null,\"sectionName\":null,\"standardType\":\"2\",\"fixStandard\":\"0\",\"maxStandard\":\"100000000\",\"minStandard\":\"0\"},{\"chitCode\":\"08500582\",\"chitName\":\"一般往来（非经营服务性收入）\",\"initCode\":\"2010102\",\"initName\":\"一般往来（非经营服务性收入）\",\"sectionCode\":null,\"sectionName\":null,\"standardType\":\"2\",\"fixStandard\":\"0\",\"maxStandard\":\"100000000\",\"minStandard\":\"0\"}]}]}";*/
            if (!ObjectUtils.isEmpty(result)) {
                JSONObject resultJO = JSONObject.parseObject(result);
                if (!ObjectUtils.isEmpty(resultJO)) {
                    Object code = resultJO.get(Constant.STRING_CODE_LOWER);
                    if (!ObjectUtils.isEmpty(code) && HttpStatus.HTTP_OK == (int) code) {
                        Object data = resultJO.get(Constant.STRING_DATA_LOWER);
                        if (ObjectUtils.isEmpty(data)) {
                            log.error("getConfigPaymentChannelInfoRegiInfo 相应data为null,msg:{}", resultJO.getString(Constant.STRING_MSG_LOWER));
                            throw new BusinessException("getConfigPaymentChannelInfoRegiInfo 相应data为null,msg:" + resultJO.getString(Constant.STRING_MSG_LOWER));
                        } else {
                            List<JSONObject> list = (List<JSONObject>) data;
                            if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                                list.forEach(e -> {
                                    BasicResultInfo basicResultInfo = JSONObject.toJavaObject(e,BasicResultInfo.class);
                                    ConfigPaymentChannelInfoVo configPaymentChannelInfoVo = new ConfigPaymentChannelInfoVo();
                                    configPaymentChannelInfoVo.setEnterCode(basicResultInfo.getEnteCode());
                                    configPaymentChannelInfoVo.setEnterName(basicResultInfo.getEnteName());
                                    configPaymentChannelInfoVo.setRegiCode(basicResultInfo.getRegiCode());
                                    configPaymentChannelInfoVo.setRegiName(basicResultInfo.getRegiName());
                                    configPaymentChannelInfoList.add(configPaymentChannelInfoVo);
                                });
                            }
                        }
                    } else {
                        log.error("getConfigPaymentChannelInfoRegiInfo 响应code:{},msg:{}", code, resultJO.getString(Constant.STRING_MESSAGE_LOWER));
                        throw new BusinessException("getConfigPaymentChannelInfoRegiInfo 响应code:" + code + ",msg:" + resultJO.getString(Constant.STRING_MESSAGE_LOWER));
                    }
                } else {
                    log.error("getConfigPaymentChannelInfoRegiInfo error(result transform JSONObject)");
                    throw new BusinessException("getConfigPaymentChannelInfoRegiInfo error(result transform JSONObject");
                }
            } else {
                log.error("getConfigPaymentChannelInfoRegiInfo result:null");
                throw new BusinessException("getConfigPaymentChannelInfoRegiInfo result:null");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            throw new BusinessException("查询缴费渠道配置信息-区域信息 " + e.getMessage());
        }
        // FIXME: 2022/3/21  先从省统一处罚正式库拿到xml数据，进行本地解析
        //configPaymentChannelInfoList = analyseUnitBasicInfo();
        return configPaymentChannelInfoList;
    }

    /**
     * 描述：同步缴费渠道配置信息
     *
     * @return {@link Result<String>} 同步结果
     * @author xiangyuyu
     * @date 2022-03-15 16:13
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Result<String> synchronizePaymentChannelConfigInfo() {
        log.info("synchronizePaymentChannelConfigInfo start ...");
        LocalDateTime startTime = LocalDateTime.now();
        CasePaymentEntRelatedBasicInfoQueryDto queryDto = new CasePaymentEntRelatedBasicInfoQueryDto();
        queryDto.setOriginalNoticeNo(CHANNEL_NO);
        List<ConfigPaymentChannelInfoVo> configPaymentChannelInfoList = getConfigPaymentChannelInfo(queryDto);
        int count = 0;
        if (!ObjectUtils.isEmpty(configPaymentChannelInfoList) && configPaymentChannelInfoList.size() > 0) {
            count = configPaymentChannelInfoList.size();
        }
        log.info("receive count:{}", count);

        //缴款渠道主干信息列表
        List<ConfigPaymentChannelInfo> mainInfoList = new ArrayList<>();
        //缴款渠道关联项目明细列表
        List<ConfigPaymentChannelItemDetail> itemInfoList = new ArrayList<>();

        configPaymentChannelInfoList.forEach(e -> {
            //缴款渠道主干信息
            ConfigPaymentChannelInfo mainInfo = new ConfigPaymentChannelInfo();
            BeanUtils.copyProperties(e, mainInfo);
            String uid = BaseUtil.createUid();
            mainInfo.setId(uid);
            mainInfoList.add(mainInfo);
            //缴款渠道关联项目明细
            List<ConfigPaymentChannelItemDetail> itemInfoTmp = e.getConfigPaymentChannelItemDetailList();
            if(!ObjectUtils.isEmpty(itemInfoTmp) && itemInfoTmp.size() > 0){
                itemInfoTmp.forEach(i -> {
                    i.setId(BaseUtil.createUid());
                    i.setPaymentChannelId(uid);
                });
                itemInfoList.addAll(itemInfoTmp);
            }
        });
        mainInfoList.forEach(e -> {
            String enterCode = e.getEnterCode();
            Example q = new Example(e.getClass());
            q.createCriteria()
                    //.andEqualTo("enterCode", e.getEnterCode())
                    //.andEqualTo("channelNo", e.getChannelNo())
                    .andEqualTo("enterName", e.getEnterName());

            int c = configPaymentChannelInfoMapper.selectCountByExample(q);
            if (c > 0) {
                e.setOpType("U");
                e.setUpdateTime(LocalDateTime.now());
                configPaymentChannelInfoMapper.updateByExampleSelective(e, q);
            } else {
                //e.setOpType("I");
                //configPaymentChannelInfoMapper.insertSelective(e);
            }
        });
        /*itemInfoList.forEach(e -> {
            Example q = new Example(e.getClass());
            q.createCriteria().andEqualTo("paymentChannelId", e.getPaymentChannelId())
                    .andEqualTo("chitCode", e.getChitCode());
            int c = configPaymentChannelItemDetailMapper.selectCountByExample(q);
            if (c > 0) {
                e.setOpType("U");
                configPaymentChannelItemDetailMapper.updateByExampleSelective(e, q);
            } else {
                e.setOpType("I");
                configPaymentChannelItemDetailMapper.insertSelective(e);
            }
        });*/
        //数据保存后期可考虑批处理操作
        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime, endTime);
        Long timeConsuming = duration.getSeconds();
        log.info("synchronizePaymentChannelConfigInfo end timeConsuming:{}", timeConsuming);
        return Result.success(Constant.STRING_OPERATE_SUCCESS);
    }

    /**
     * 【V1.0.0】描述：同步缴费渠道配置信息-同步区域编码信息
     *
     * @return {@link Result<String>} 同步结果
     * @author xiangyuyu
     * @date 2022-03-15 16:13
     */
    @Override
    public Result<String> synchronizePaymentChannelConfigInfoRegiInfo() {
        log.info("synchronizePaymentChannelConfigInfoRegiInfo start ...");
        LocalDateTime startTime = LocalDateTime.now();
        CasePaymentEntRelatedBasicInfoQueryDto queryDto = new CasePaymentEntRelatedBasicInfoQueryDto();
        queryDto.setOriginalNoticeNo(CHANNEL_NO);
        List<ConfigPaymentChannelInfoVo> configPaymentChannelInfoList = getConfigPaymentChannelInfoRegiInfo(queryDto);
        int count = 0;
        if (!ObjectUtils.isEmpty(configPaymentChannelInfoList) && configPaymentChannelInfoList.size() > 0) {
            count = configPaymentChannelInfoList.size();
        }
        log.info("receive count:{}", count);

        //缴款渠道主干信息列表
        List<ConfigPaymentChannelInfo> mainInfoList = new ArrayList<>();
        //缴款渠道关联项目明细列表
        List<ConfigPaymentChannelItemDetail> itemInfoList = new ArrayList<>();

        configPaymentChannelInfoList.forEach(e -> {
            //缴款渠道主干信息
            ConfigPaymentChannelInfo mainInfo = new ConfigPaymentChannelInfo();
            BeanUtils.copyProperties(e, mainInfo);
            String uid = BaseUtil.createUid();
            mainInfo.setId(uid);
            mainInfoList.add(mainInfo);
            //缴款渠道关联项目明细
            List<ConfigPaymentChannelItemDetail> itemInfoTmp = e.getConfigPaymentChannelItemDetailList();
            if(!ObjectUtils.isEmpty(itemInfoTmp) && itemInfoTmp.size() > 0){
                itemInfoTmp.forEach(i -> {
                    i.setId(BaseUtil.createUid());
                    i.setPaymentChannelId(uid);
                });
                itemInfoList.addAll(itemInfoTmp);
            }
        });
        mainInfoList.forEach(e -> {
            String enterCode = e.getEnterCode();
            Example q = new Example(e.getClass());
            q.createCriteria()
                    //.andEqualTo("enterCode", e.getEnterCode())
                    //.andEqualTo("channelNo", e.getChannelNo())
                    .andEqualTo("enterName", e.getEnterName());

            int c = configPaymentChannelInfoMapper.selectCountByExample(q);
            if (c > 0) {
                e.setOpType("U");
                e.setUpdateTime(LocalDateTime.now());
                configPaymentChannelInfoMapper.updateByExampleSelective(e, q);
            } else {
                //e.setOpType("I");
                //configPaymentChannelInfoMapper.insertSelective(e);
            }
        });
        /*itemInfoList.forEach(e -> {
            Example q = new Example(e.getClass());
            q.createCriteria().andEqualTo("paymentChannelId", e.getPaymentChannelId())
                    .andEqualTo("chitCode", e.getChitCode());
            int c = configPaymentChannelItemDetailMapper.selectCountByExample(q);
            if (c > 0) {
                e.setOpType("U");
                configPaymentChannelItemDetailMapper.updateByExampleSelective(e, q);
            } else {
                e.setOpType("I");
                configPaymentChannelItemDetailMapper.insertSelective(e);
            }
        });*/
        //数据保存后期可考虑批处理操作
        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime, endTime);
        Long timeConsuming = duration.getSeconds();
        log.info("synchronizePaymentChannelConfigInfoRegiInfo end timeConsuming:{}", timeConsuming);
        return Result.success(Constant.STRING_OPERATE_SUCCESS);
    }

    /**
     * 描述：查询缴款渠道配置信息
     *
     * @param queryDto {@link ConfigPaymentChannelInfoQueryDto}
     * @return {@link List< ConfigPaymentChannelInfoVo >} 缴款渠道配置信息
     * @author xiangyuyu
     * @date 2022-03-01 16:51
     */
    @Override
    public List<ConfigPaymentChannelInfoVo> getPaymentChannelConfigInfo(ConfigPaymentChannelInfoQueryDto queryDto) {
        String channelNo = queryDto.getChannelNo();
        if (ObjectUtils.isEmpty(channelNo)) {
            throw new BusinessException("未指定来源渠道编码");
        }
        List<ConfigPaymentChannelInfoVo> configPaymentChannelInfoList=new ArrayList<>();
        if(!StringUtils.isBlank(queryDto.getDeptCode())){
            configPaymentChannelInfoList
                    = configPaymentChannelInfoMapper.selectPaymentChannelConfigInfo(queryDto);
            if(!ObjectUtils.isEmpty(configPaymentChannelInfoList)){
                return configPaymentChannelInfoList;
            }
        }
        queryDto.setDeptCode("");
        configPaymentChannelInfoList
                = configPaymentChannelInfoMapper.selectPaymentChannelConfigInfo(queryDto);
        return configPaymentChannelInfoList;
    }


    /**
     * 描述：保存缴款渠道配置信息
     *
     * @param configPaymentChannelInfo {@link ConfigPaymentChannelInfo}
     * @return Boolean 保存结果
     * @author xiangyuyu
     * @date 2022-03-01 16:51
     */
    @Override
    public Boolean savePaymentChannelConfigInfo(ConfigPaymentChannelInfo configPaymentChannelInfo) {
        ConfigPaymentChannelInfoQueryDto queryDto = new ConfigPaymentChannelInfoQueryDto();
        String channelNo = configPaymentChannelInfo.getChannelNo();
        String entCode = configPaymentChannelInfo.getEnterCode();
        if (ObjectUtils.isEmpty(channelNo)) {
            throw new BusinessException("未指定来源渠道编码");
        }
        if (ObjectUtils.isEmpty(entCode)) {
            throw new BusinessException("未指定企业编码");
        }
        queryDto.setChannelNo(channelNo);
        queryDto.setEnterCode(entCode);
        //根据唯一索引查询记录数
        List<ConfigPaymentChannelInfoVo> configPaymentChannelInfoList = getPaymentChannelConfigInfo(queryDto);
        if (ObjectUtils.isEmpty(configPaymentChannelInfoList) || configPaymentChannelInfoList.size() == 0) {
            //I
            configPaymentChannelInfo.setOpType("I");
        } else {
            //U(暂不考虑删除)
            Example updateExample = new Example(ConfigPaymentChannelInfo.class);
            updateExample.createCriteria().andEqualTo("noticeNo", channelNo)
                    .andEqualTo("entCode", entCode);
            configPaymentChannelInfo.setOpType("U");
            configPaymentChannelInfoMapper.updateByExampleSelective(configPaymentChannelInfo, updateExample);
        }
        return true;
    }

    /**
     * 描述：解析执收单位基础信息（本地xml文件）
     *
     * @return {@link List<ConfigPaymentChannelInfoVo>} 执收单位基础信息
     * @author xiangyuyu
     * @date 2022-03-21 09:50
     */
    public static List<ConfigPaymentChannelInfoVo> analyseUnitBasicInfo() {
        List<ConfigPaymentChannelInfoVo> configPaymentChannelInfoList = new ArrayList<>();
        List<String> distinctSignList = new ArrayList<>();
        try {
            SAXBuilder builder = new SAXBuilder();
            org.jdom.Document doc = builder.build(new File("/Users/amelia/Documents/icinfo/punish-new/unified-punish-case/unified-punish-case-provider/src/main/resources/json.xml"));
            org.jdom.Element foo = doc.getRootElement();
            List result = foo.getContent();
            Element response = (Element) ((Element) result.get(3)).getContent().get(0);
            List detailList = response.getContent();
            detailList.forEach(e -> {
                Element entInfo = (Element) e;
                List<Element> attributes = entInfo.getContent();
                ConfigPaymentChannelInfoVo configPaymentChannelInfoVo = new ConfigPaymentChannelInfoVo();
                List<ConfigPaymentChannelItemDetail> configPaymentChannelItemDetailList = new ArrayList<>();
                attributes.forEach(attr -> {
                    String key = attr.getName();
                    String value = attr.getValue();
                    ConfigPaymentChannelItemDetail detail = new ConfigPaymentChannelItemDetail();
                    if ("CHANNELNO".equals(key)) {
                        configPaymentChannelInfoVo.setChannelNo(value);
                    } else if ("CHANNELNAME".equals(key)) {
                        configPaymentChannelInfoVo.setChannelName(value);
                    } else if ("REGICODE".equals(key)) {
                        configPaymentChannelInfoVo.setRegiCode(value);
                    } else if ("REGINAME".equals(key)) {
                        configPaymentChannelInfoVo.setRegiName(value);
                    } else if ("ENTECODE".equals(key)) {
                        configPaymentChannelInfoVo.setEnterCode(value);
                    } else if ("ENTENAME".equals(key)) {
                        configPaymentChannelInfoVo.setEnterName(value);
                    } else if ("PROJECT".equals(key)) {
                        List<Element> projectAttrList = attr.getContent();
                        if (!ObjectUtils.isEmpty(projectAttrList) && projectAttrList.size() > 0) {
                            projectAttrList.forEach(pa -> {
                                String k = pa.getName();
                                String v = pa.getValue();
                                if ("CHITCODE".equals(k)) {
                                    detail.setChitCode(v);
                                } else if ("CHITNAME".equals(k)) {
                                    detail.setChitName(v);
                                } else if ("INITCODE".equals(k)) {
                                    detail.setInitCode(v);
                                } else if ("INITNAME".equals(k)) {
                                    detail.setInitName(v);
                                } else if ("SECTIONCODE".equals(k)) {
                                    detail.setSectionCode(v);
                                } else if ("SECTIONNAME".equals(k)) {
                                    detail.setSectionName(v);
                                }
                                //STANDARDTYPE,FIXSTANDARD,MAXSTANDARD,MINSTANDARD
                            });
                            configPaymentChannelItemDetailList.add(detail);
                        }
                        configPaymentChannelInfoVo.setConfigPaymentChannelItemDetailList(configPaymentChannelItemDetailList);
                    }
                });
                //channelNo,enterCode,enterName
                String distinctSign = configPaymentChannelInfoVo.getChannelNo()
                        +","+configPaymentChannelInfoVo.getEnterCode()+","+configPaymentChannelInfoVo.getEnterName();
                if(!distinctSignList.contains(distinctSign)){
                    distinctSignList.add(distinctSign);
                    configPaymentChannelInfoList.add(configPaymentChannelInfoVo);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析本地执收单位基础信息时出现异常 error:{}", e.getMessage());
        }
        return configPaymentChannelInfoList;
    }

    /**
     * 【V2.0.0】描述：根据机构编码查询机构缴款配置信息
     *
     * @param orgCode 机构编码
     * @return {@link Result<ConfigPaymentChannelInfoVo>} 缴款渠道配置信息
     * @author xiangyuyu
     * @date 2022-05-19 14:47
     */
    @Override
    public ConfigPaymentChannelInfoVo getPaymentChannelConfigInfoByOrgCode(String orgCode,String deptCode) {
        if (ObjectUtils.isEmpty(orgCode)) {
            throw new BusinessException("未指定机构编码");
        }
        /*Example query = new Example(ConfigPaymentChannelInfo.class);
        query.createCriteria().andEqualTo("orgCode", orgCode);

        List<ConfigPaymentChannelInfo> configPaymentChannelInfoList = configPaymentChannelInfoMapper.selectByExample(query);
        ConfigPaymentChannelInfoVo vo = new ConfigPaymentChannelInfoVo();
        if (!ObjectUtils.isEmpty(configPaymentChannelInfoList) && configPaymentChannelInfoList.size() > 0) {
            ConfigPaymentChannelInfo configPaymentChannelInfo = configPaymentChannelInfoList.get(Constant.INTEGER_0);
            if (!ObjectUtils.isEmpty(configPaymentChannelInfo)) {
                BeanUtils.copyProperties(configPaymentChannelInfo, vo);
            }
        }*/
        ConfigPaymentChannelInfoVo vo = new ConfigPaymentChannelInfoVo();
        List<ConfigPaymentChannelInfo> configPaymentChannelInfos=new ArrayList<>();
        ConfigPaymentChannelInfo configPaymentChannelInfo=new ConfigPaymentChannelInfo();
        Example example = new Example(ConfigPaymentChannelInfo.class);
        example.createCriteria().andEqualTo("orgCode",orgCode).andCondition("(dept_code is null or dept_code='') ");
        configPaymentChannelInfos = configPaymentChannelInfoMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(configPaymentChannelInfos)){
            configPaymentChannelInfo = configPaymentChannelInfos.get(Constant.INTEGER_0);
        }
        if(StringUtils.isNotBlank(deptCode)) {
            Example deptExample = new Example(ConfigPaymentChannelInfo.class);
            deptExample.createCriteria().andEqualTo("orgCode", orgCode).andEqualTo("deptCode", deptCode);
            List<ConfigPaymentChannelInfo> configPaymentChannelInfoDepts = configPaymentChannelInfoMapper.selectByExample(deptExample);
            if (!ObjectUtils.isEmpty(configPaymentChannelInfoDepts)) {
                configPaymentChannelInfo = configPaymentChannelInfoDepts.get(0);
            }
        }
        BeanUtils.copyProperties(configPaymentChannelInfo, vo);
        return vo;
    }
}